<template>
  <main-content-search-bar-wrapper>
    <search-bar>
      <template #normal>
        <el-form-item label="任务名称">
          <el-input v-model="searchForm.name" placeholder="请输入任务名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="任务类型">
          <el-select v-model="searchForm.taskType" clearable>
            <el-option v-for="(item, index) in taskTypeList" :value="item.value" :label="item.label" :key="index">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务分类">
          <el-select v-model="searchForm.categoryInfoId" clearable>
            <el-option v-for="(item, index) in categoryList" :value="item.id" :label="item.categoryName" :key="index">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务状态">
          <el-select v-model="searchForm.status" clearable>
            <el-option v-for="(item, index) in taskOnlineStatus" :label="item.label" :value="item.value" :key="index">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="refreshList">查询</el-button>
          <el-button type="primary" @click="createRankTask" v-has="['10100107']">新增任务</el-button>
          <!-- TODO 加权限 -->
          <el-button type="primary" @click="showExportData = true">导出</el-button>
        </el-form-item>
      </template>
    </search-bar>
  </main-content-search-bar-wrapper>

  <layout-table ref="rankTaskTableRef" url="/merchant/memTask/queryPageTask" :param="searchForm" :hide-init="true"
    :set-search="manullySearch">
    <el-table-column label="任务名称" prop="name" min-width="180"></el-table-column>
    <el-table-column label="任务描述" prop="description" min-width="200"></el-table-column>
    <el-table-column label="任务图标" prop="img" min-width="150">
      <template #default="scope">
        <el-image fit="contain" :src="scope.row.img" style="width: 80px; height: 80px"></el-image>
      </template>
    </el-table-column>
    <el-table-column label="所属分类" prop="categoryName" width="180"></el-table-column>
    <el-table-column label="任务类型" prop="" width="180">
      <template #default="scope">
        {{ getTaskTypeLabel(scope.row.taskType) }}
      </template>
    </el-table-column>
    <!--    <el-table-column label="限制条件" prop="status" width="120"></el-table-column>-->
    <!--    <el-table-column label="完成奖励" prop="categoryIds" min-width="150"></el-table-column>-->
    <el-table-column label="创建时间" prop="createTime" width="180">
      <template #default="scope">
        {{ formatTime(scope.row.createTime) }}
      </template>
    </el-table-column>
    <el-table-column label="状态" prop="status" min-width="150">
      <template #default="scope">
        <el-switch v-model="scope.row.status" v-loading="scope.row.statusLoading"
          :before-change="() => _changeTaskStatus(scope.row)" active-text="启用" inactive-text="未启用" inline-prompt
          :active-value="1" :inactive-value="0">
        </el-switch>
      </template>
    </el-table-column>
    <el-table-column label="操作" fixed="right" width="180" v-has="['10100108', '10100109']">
      <template #default="scope">
        <el-button link type="primary" @click="editRankTask(scope.row)" v-has="['10100108']">编辑</el-button>
        <el-button link type="primary" @click="goTaskRecord(scope.row)" v-has="['10100109']">任务记录</el-button>
      </template>
    </el-table-column>
  </layout-table>

  <rank-task-edit-dialog :mode="dialogMode" v-model:show="isShowEditRankTaskDialog" :row-data="operatingRow"
    :selected-rank="props.selectedRank" @confirm="refreshList"></rank-task-edit-dialog>
  <exportData v-model:show-dialog="showExportData" :search-data="searchForm" title="等级任务" export-type="memberTaskExport">
  </exportData>
</template>

<script lang="ts" setup>
import { Ref } from 'vue'
import { IRankBenefitItem, IRankItem, IRankTaskData, IRankTaskItem } from "@/api/modules/vipCenter";
import { useTaskType } from "@/views/taskCenter/compositions/useTaskType";
import { useTaskOnlineStatus } from "@/views/taskCenter/compositions/useTaskOnlineStatus";
import { useTaskCategory } from "@/views/taskCenter/compositions/useTaskCategory";
import { changeTaskStatus } from "@/api/vipCenter";
import RankTaskEditDialog from "@/views/vipCenter/components/RankTaskEditDialog.vue";
import moment from "moment";
import { ITaskListItem } from "@/api/modules/taskCenter";
import exportData from "@/components/exportData/exportData.vue";
const router = useRouter()
const route = useRoute()

const props = defineProps<{
  selectedRank: IRankItem
}>()
const selectedRankRef = toRef(props, 'selectedRank')
// 任务类型查询条件 选项
const { taskTypeList, getTaskTypeLabel } = useTaskType()
// 任务状态查询条件 选项
const { taskOnlineStatus } = useTaskOnlineStatus()
// 任务分类查询条件 选项
const { categoryList, getTaskCategory } = useTaskCategory()
const showExportData = ref(false)
const searchForm = reactive<IRankTaskData>({
  memberId: null,
  name: '',
  categoryInfoId: [],
  taskType: '',
  status: null,
  // insId: [],
})

const operatingRow = ref()
const dialogMode = ref<'edit' | 'create'>('create')

const isShowEditRankTaskDialog: Ref<boolean> = ref(false)
const createRankTask = () => {
  dialogMode.value = 'create'
  isShowEditRankTaskDialog.value = true
}

const editRankTask = (rowData: IRankTaskItem) => {
  dialogMode.value = 'edit'
  isShowEditRankTaskDialog.value = true
  operatingRow.value = rowData
}

const goTaskRecord = (rowData: IRankTaskItem) => {
  router.push({
    path: '/merchant/task_center/task_record',
    query: {
      taskName: rowData.name
    }
  })
}

const _changeTaskStatus = async (rowData: IRankTaskItem) => {
  const rs = await changeTaskStatus({ id: rowData.id, name: rowData.name })
  if (rs.code === 200) {
    ElMessage.success('修改成功')
    return true
  } else {
    ElMessage.error(rs.errorMsg)
    return false
  }
}

const formatTime = (val: number) => {
  return val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : ''
}

const manullySearch: Ref<number> = ref(0)
const refreshList = () => {
  ++manullySearch.value
}

const store = useStore();
// 监听机构
const insId = computed(() => {
  return store.state.insId.insId;
});
watch(
  () => insId,
  async () => {
    refreshList()
  },
  {
    deep: true
  }
)

watch(selectedRankRef, (newValue) => {
  getTaskCategory() // 任务分类，所属分类
  searchForm.memberId = newValue.id // 触发搜索
})

onMounted(() => {
  getTaskCategory() // 任务分类，所属分类
  searchForm.memberId = selectedRankRef.value.id // 触发搜索
})
</script>

<style scoped lang="scss"></style>
